package com.magesti.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.magesti.ressource.Global;

@SuppressWarnings("serial")
public class Deconnexion extends HttpServlet {
	
	public void init() throws ServletException {

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpSession session = request.getSession();
		destroyCookie(response, request, Global.ATT_COOKIE_NOM_UTILISATEUR);
		session.invalidate();
		response.sendRedirect(request.getContextPath() + Global.VUE_SERV_CONNEXION);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	private void destroyCookie(HttpServletResponse response,
			HttpServletRequest request, String attCookieNomUtilisateur) {
		// Code repris depuis setCookie dans connexion.
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie != null
						&& Global.ATT_COOKIE_NOM_UTILISATEUR.equals(cookie.getName())) {
					// session.setAttribute(ATT_SESSION_UTILISATEUR,
					// cookie.getValue());
					cookie.setMaxAge(0);
					cookie.setValue("");
					cookie.setPath("/");
					response.addCookie(cookie);
				}
			}
		}

	}

}
